package cn.sc.listener;

import cn.sc.jedis.config.ClusterInfo;
import cn.sc.jedis.config.RedisInfo;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;


/**
 * @ClassName SimpleCacheInitListener
 * @Author 谢卓才
 * @Description springboot发布事件，处理redis修改配置信息
 * @Date 2022/11/13 9:17
 */
public class SimpleCacheInitListener implements GenericApplicationListener {

    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(eventType.getRawClass());
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if(event instanceof ApplicationEnvironmentPreparedEvent){
            ConfigurableEnvironment environment = ((ApplicationEnvironmentPreparedEvent) event).getEnvironment();
            RedisInfo redisInfo = new RedisInfo();
            Binder.get(environment).bind("redis", Bindable.ofInstance(redisInfo));
            ClusterInfo clusterInfo = new ClusterInfo();
            Binder.get(environment).bind("redis.cluster", Bindable.ofInstance(clusterInfo));
            redisInfo.setCluster(clusterInfo);
            RedisInfo.setGlobalRedisInfo(redisInfo);
        }
    }

}
